// stores/counter.js
import { defineStore } from 'pinia';
import auth from "@/utils/auth.js";
import apis from "@/apis/index.js";
import utils from "@/utils/utils";
import atlas from "@/utils/atlas.js";//地图相关方法
import config from "@/config/index.js";


//uni_modules方式导入SDK
import { YeIMUniSDK, YeIMUniSDKDefines } from '@/uni_modules/wzJun1-YeIM-Uni-SDK/js_sdk/yeim-uni-sdk.min.js'



const useCounterStore = defineStore('YeIM', {
  state: () => ({
    YeIM: null,
    news: {},//收到的新消息
    chats: [],//会话列表
  }),

  getters: {
    noReadNum: (state) => {
      let num = 0
      state.chats.forEach(element => {
        num += element.unread
      });
      return num;
    },
  },

  actions: {
    // 初始化IM
    async initIm() {
      YeIMUniSDK.init({
        baseURL: `http://47.95.197.43:18011`, // YeIMServer http url （如无特殊需求，服务端启动后仅需修改ip或者域名即可）
        socketURL: `ws://47.95.197.43:18011/im`, // YeIMServer socket url（如无特殊需求，服务端启动后仅需修改ip或者域名即可）
        logLevel: 1, // SDK日志等级，0 = 打印全部日志， 1 = 打印重要日志，2 = 不打印日志
        reConnectInterval: 3000, // 断线重连时间间隔（遇到网络波动，IM服务端可能会断线，此时需要重新连接到服务端），单位：毫秒
        reConnectTotal: 0, // 最大重连次数，0不限制一直重连 
        heartInterval: 30000, //心跳时间间隔（默认30秒），单位：毫秒
        notification: {
          autoPermission: true //IM登录后是否自动检测通知权限
        }
      });
    },

    //init
    async init() {
      await this.initIm()
      setTimeout(() => {
        this.login()
      }, 1000);
    },

    login() {
      let code = YeIMUniSDK.getInstance().readyState();
      //0：连接中   1：连接打开  2：连接关闭中  3：连接关闭
      if (code == 1) return
      let slParams = uni.getStorageSync("slParams")
      let { token, userId } = slParams
      YeIMUniSDK.getInstance().connect({
        userId: userId.toString(), token,
        success: (response) => {
          if (response.code == 200) {
            console.log("登录成功：", response);
            this.addEventListenerFunc()
            //this.sendMessage("59", { text: "你好，欢迎使用YeIM" }, 'text')
          }
        },
        fail: (err) => {
          console.log("登陆失败：", err);
        }
      });
    },

    //创建文字消息
    createText(toId, body) {
      let message = YeIMUniSDK.getInstance().createTextMessage({
        toId, //接收者用户ID字符串
        conversationType: YeIMUniSDKDefines.CONVERSATION_TYPE.PRIVATE, //会话类型：私聊
        body
      });
      return message
    },

    //创建语音直发消息
    createAudio(imUid, body) {
      let message = YeIMUniSDK.getInstance().createAudioMessageFromUrl({
        toId: imUid, //接收者用户ID字符串
        conversationType: YeIMUniSDKDefines.CONVERSATION_TYPE.PRIVATE, //会话类型：私聊
        body,
        extra: "这是拓展的自定义的内容"
      });

      return message
    },

    //创建图片
    createImage(imUid, body) {
      let query = utils.deepcopy(body)
      delete query.extra
      let message = YeIMUniSDK.getInstance().createImageMessage({
        toId: imUid, //接收者用户ID字符串
        conversationType: YeIMUniSDKDefines.CONVERSATION_TYPE.PRIVATE, //会话类型：私聊
        body: query,
        extra: body.extra,
        onProgress: (progress) => {
          console.log('上传进度' + progress.progress);
          console.log('已经上传的数据长度' + progress.totalBytesSent);
          console.log('预期需要上传的数据总长度' + progress.totalBytesExpectedToSend);
        }
      });
      return message
    },

    //创建地理位置消息
    createLocationMessage(toId, body) {
      //创建位置消息
      let message = YeIMUniSDK.getInstance().createLocationMessage({
        toId, //接收者用户ID字符串
        conversationType: YeIMUniSDKDefines.CONVERSATION_TYPE.PRIVATE, //会话类型：私聊
        body,
        extra: "这是拓展的自定义的内容",
      });
      return message
    },

    //发送消息
    async sendMessage(imUid, body, type) {
      let message
      switch (type) {
        case "text":
          message = this.createText(imUid, body)
          break;
        case "image":
          message = this.createImage(imUid, body)
          break;
        case "audio":
          message = this.createAudio(imUid, body)
          break;
        case "location": //地理位置
          message = this.createLocationMessage(imUid, body)
          break;
        default:
          break;
      }
      return new Promise((resolve, reject) => {
        //发送消息
        YeIMUniSDK.getInstance().sendMessage({
          message: message,
          success: (res) => {
            console.log("发送成功", res)
            resolve(res)
          },
          fail: (err) => {
            console.log("发送失败", err)
            if (err.code == 10003) {
              this.openCheck()
            }
            reject(err)
          }
        });
      })
    },


    //添加好友
    addFriend(userId, remark) {
      return new Promise((resolve, reject) => {
        YeIMUniSDK.getInstance().addFriend({
          userId,
          remark,
          extraMessage: "",
          success: (res) => {
            console.log("添加好友", res)
            resolve(res)
            //当返回的状态码为：20020，表示对方开启了好友申请验证，需等待对方处理同意或拒绝。并且触发事件：YeIMUniSDKDefines.EVENT.FRIEND_APPLY_LIST_CHANGED
          },
          fail: (err) => {
            reject(err)
          }
        });
      })
    },

    //获取好友申请列表
    getFriendApplyList(page, type) {
      return new Promise((resolve, reject) => {
        YeIMUniSDK.getInstance().getFriendApplyList({
          page,
          limit: 20,
          type,
          cloud: true,
          success: (res) => {
            resolve(res)
          },
          fail: (err) => {
            reject(err)
          }
        });
      })
    },

    //同意好友申请
    acceptApply(id) {
      return new Promise((resolve, reject) => {
        YeIMUniSDK.getInstance().acceptApply({
          id,
          remark: '',
          success: (res) => {
            resolve(res)
          },
          fail: (err) => {
            reject(err)
          }
        });
      })
    },

    //拒绝好友申请
    refuseApply(id) {
      return new Promise((resolve, reject) => {
        YeIMUniSDK.getInstance().refuseApply({
          id,
          success: (res) => {
            resolve(res)
          },
          fail: (err) => {
            reject(err)
          }
        });
      })
    },

    //获取好友列表
    getFriendList(page) {
      return new Promise((resolve, reject) => {
        YeIMUniSDK.getInstance().getFriendList({
          page,
          limit: 20,
          cloud: true,
          success: (res) => {
            resolve(res)
          },
          fail: (err) => {
            reject(err)
          }
        });
      })
    },

    //获取历史消息记录
    getHistoryMessageList(conversationId, nextMessageId) {
      return new Promise((resolve, reject) => {
        YeIMUniSDK.getInstance().getHistoryMessageList({
          nextMessageId,
          conversationId,
          limit: 100,
          success: (res) => {
            resolve(res)
          },
          fail: (err) => {
            reject(err)
          }
        });
      })
    },

    //清除指定会话未读数，并给对方发送已读回执
    clearConversationUnread(id) {
      YeIMUniSDK.getInstance().clearConversationUnread(id);
    },

    //监听器
    addEventListenerFunc() {
      //监听会话列表更新
      YeIMUniSDK.getInstance().addEventListener(YeIMUniSDKDefines.EVENT.CONVERSATION_LIST_CHANGED, (list) => {
        console.log("监听会话列表更新:", list)
        this.chats = list
        let num = 0
        list.forEach(element => {
          num += element.unread
        });
        //如果有未读消息，显示小红点
        if (num) {
          uni.showTabBarRedDot({ index: 2 });
        } else {
          uni.hideTabBarRedDot({ index: 2 })
        }
      });

      //监听新消息接收
      YeIMUniSDK.getInstance().addEventListener(YeIMUniSDKDefines.EVENT.MESSAGE_RECEIVED, (list) => {
        console.log("收到新消息:", list)
        this.news = list
      });

      //监听私聊会话已读回执，对端调用 clearConversationUnread 接口时触发
      YeIMUniSDK.getInstance().addEventListener(YeIMUniSDKDefines.EVENT.PRIVATE_READ_RECEIPT, (res) => {
        console.log("收到私聊会话已读回执:", res)
      });

      //监听消息撤回事件
      YeIMUniSDK.getInstance().addEventListener(YeIMUniSDKDefines.EVENT.MESSAGE_REVOKED, (res) => {
        console.log("收到消息撤回事件:", res)
      });

      //好友列表变化
      YeIMUniSDK.getInstance().addEventListener(YeIMUniSDKDefines.EVENT.FRIEND_LIST_CHANGED, (res) => {
        console.log("收到好友列表变化事件:")
        console.log(res)
      });

      //好友申请列表变化
      YeIMUniSDK.getInstance().addEventListener(YeIMUniSDKDefines.EVENT.FRIEND_APPLY_LIST_CHANGED, (res) => {
        console.log("收到好友申请列表变化事件:", res)
      });

      //好友申请被拒
      YeIMUniSDK.getInstance().addEventListener(YeIMUniSDKDefines.EVENT.FRIEND_APPLY_REFUSE, (res) => {
        console.log("收到好友申请被拒事件:", res)
      });

      //监听SDK网络连接状态
      YeIMUniSDK.getInstance().addEventListener(YeIMUniSDKDefines.EVENT.NET_CHANGED, (res) => {
        console.log("网络状态变化:" + res)
      });

      //监听登陆互踢，当同一用户重复登录时触发
      YeIMUniSDK.getInstance().addEventListener(YeIMUniSDKDefines.EVENT.KICKED_OUT, () => {
        console.log("用户被踢下线")
      });

      //添加一个网络状态变化的监听器
      YeIMUniSDK.getInstance().addEventListener(YeIMUniSDKDefines.EVENT.NET_CHANGED, this.netChanged);
      //移除了这个网络状态变化的监听器
      YeIMUniSDK.getInstance().removeEventListener(YeIMUniSDKDefines.EVENT.NET_CHANGED, this.netChanged);

      var netChanged = function (res) {
        console.log("网络状态变化:" + res);
      }
    }
  },
});

export default useCounterStore
